package com.xxx.video.mine.activitys;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.xxx.video.R;
import com.xxx.video.commen.activitys.BaseActivity;
import com.xxx.video.commen.adapters.BaseRecycleViewAdapter;
import com.xxx.video.commen.utils.FontCacheUtils;
import com.xxx.video.commen.utils.ListUtils;
import com.xxx.video.commen.utils.StatusBarUtil;
import com.xxx.video.commen.utils.StringUtils;
import com.xxx.video.commen.utils.SystemActivityUtils;
import com.xxx.video.commen.utils.ToastUtils;
import com.xxx.video.commen.utils.UriUtils;
import com.xxx.video.commen.views.FontTextView;
import com.xxx.video.commen.views.IosSingleChoosePopupWindow;
import com.xxx.video.mine.adapters.FeedBackPhotoListAdapter;
import com.xxx.video.mine.adapters.FeedBackTypeListAdapter;
import com.xxx.video.mine.beans.FeedBackImageBean;
import com.xxx.video.mine.beans.FeedBackTypeListBean;
import com.xxx.video.mine.presenters.FeedBackPresenter;
import com.xxx.video.mine.presenters.IFeedBackView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;

public class FeedBackActivity extends BaseActivity<FeedBackPresenter> implements IFeedBackView,
        BaseRecycleViewAdapter.OnItemClickListener, IosSingleChoosePopupWindow.OnIosSingleChooseItemClickListener {
    /**
     * start camera activity request code
     */
    public static final int START_CAMERA_ACTIVITY = 201;
    /**
     * start album activity request code
     */
    public static final int START_ALBUM_ACTIVITY = 202;
    /**
     * request permission
     */
    public static final int REQUEST_PERMISSION_CODE = 200;

    String[] permissions = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"
    };
    @BindView(R.id.et_feed_back_activity_feed_back_description)
    EditText etFeedBackActivityFeedBackDescription;
    @BindView(R.id.rcv_feed_back_activity_feed_back_photo_list)
    RecyclerView rcvFeedBackActivityFeedBackPhotoList;
    @BindView(R.id.et_feed_back_activity_feed_back_email)
    EditText etFeedBackActivityFeedBackEmail;
    @BindView(R.id.tv_feed_back_activity_feed_back_submit)
    TextView tvFeedBackActivityFeedBackSubmit;
    @BindView(R.id.iv_actionbar_left_icon)
    ImageView ivActionbarLeftIcon;
    @BindView(R.id.rcv_feed_back_activity_feed_back_type_list)
    RecyclerView rcvFeedBackActivityFeedBackTypeList;
    /**
     * use camera save image file path
     */
    private String mImageFilePath;
    /**
     * feedBack photo list adapter
     */
    private FeedBackPhotoListAdapter mFeedBackPhotoListAdapter;
    /**
     * check type list bean
     */
    private FeedBackTypeListBean.ListBean mCheckFeedBackTypeListBean;

    @Override
    public void initToolbarData() {
        super.initToolbarData();
        showActionBar();
        StatusBarUtil.getInstance().setStatusBarTransparent(this, true);
        setIsShowActionbarLine(true);
        setActionBarTitle(R.string.title_feed_back_activity);
        Typeface customFont = FontCacheUtils.getInstance().getTypeface(FontTextView.ttf3, this);
        etFeedBackActivityFeedBackDescription.setTypeface(customFont);
        etFeedBackActivityFeedBackEmail.setTypeface(customFont);
    }

    @Override
    protected FeedBackPresenter createPresenter() {
        return new FeedBackPresenter(this, this);
    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_feed_back;
    }

    @Override
    public void initData(Bundle extras) {
        getPresenter().getFeedBackTypeList();
        initFeedBackPhotoList();
    }

    @OnTextChanged(R.id.et_feed_back_activity_feed_back_description)
    public void onTextChanged() {
        if (TextUtils.isEmpty(getFeedBackContent())) {
            tvFeedBackActivityFeedBackSubmit.setEnabled(false);
        } else {
            tvFeedBackActivityFeedBackSubmit.setEnabled(true);
        }
    }

    @OnClick({R.id.iv_actionbar_left_icon, R.id.tv_actionbar_left_tile,
            R.id.tv_feed_back_activity_feed_back_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_actionbar_left_icon:
            case R.id.tv_actionbar_left_tile:
                onBackPressed();
                break;
            case R.id.tv_feed_back_activity_feed_back_submit:
                getPresenter().submitFeedBack();
                break;
            default:
                break;
        }
    }

    @Override
    public void showRootLayoutStatus(int status) {
        showLayoutStatus(status);
    }

    @Override
    public void initFeedBackPhotoList() {
        rcvFeedBackActivityFeedBackPhotoList.setLayoutManager(new GridLayoutManager(this, 4));
        mFeedBackPhotoListAdapter = new FeedBackPhotoListAdapter(this);
        mFeedBackPhotoListAdapter.setOnItemClickListener(this);
        rcvFeedBackActivityFeedBackPhotoList.setAdapter(mFeedBackPhotoListAdapter);
    }

    @Override
    public void initFeedBackTypeListData2View(FeedBackTypeListBean successOb) {
        rcvFeedBackActivityFeedBackTypeList.setLayoutManager(new GridLayoutManager(this, 2));
        FeedBackTypeListAdapter feedBackTypeListAdapter = new FeedBackTypeListAdapter(this);
        feedBackTypeListAdapter.setData(successOb.list);
        feedBackTypeListAdapter.setOnItemClickListener((BaseRecycleViewAdapter.OnItemClickListener<FeedBackTypeListBean.ListBean>) (listBean, position, type) -> mCheckFeedBackTypeListBean = listBean);
        rcvFeedBackActivityFeedBackTypeList.setAdapter(feedBackTypeListAdapter);
        if (!ListUtils.isEmpty(successOb.list)) {
            mCheckFeedBackTypeListBean = successOb.list.get(0);
        }
    }

    @Override
    public String getEmail() {
        return etFeedBackActivityFeedBackEmail.getText().toString().trim();
    }

    @Override
    public String getFeedBackContent() {
        return etFeedBackActivityFeedBackDescription.getText().toString().trim();
    }

    @Override
    public FeedBackTypeListBean.ListBean getFeedBackType() {
        return mCheckFeedBackTypeListBean;
    }

    @Override
    public void feedBackSuccess() {
        ToastUtils.showSuccess(StringUtils.getInstance().getString(R.string.tip_feed_back_success));
        finish();
    }

    @Override
    public List<FeedBackImageBean> getFeedBackImageList() {
        if (mFeedBackPhotoListAdapter != null) {
            return mFeedBackPhotoListAdapter.data;
        }
        return null;
    }

    @Override
    public void onItemClick(Object o, int position, int type) {
        IosSingleChoosePopupWindow iosSingleChooseDialog = new IosSingleChoosePopupWindow(this);
        ArrayList<String> stringArrayList = new ArrayList<>();
        stringArrayList.add(StringUtils.getInstance().getString(R.string.dialog_choose_album));
        iosSingleChooseDialog.setData(StringUtils.getInstance().getString(R.string.dialog_choose_camera), StringUtils.getInstance().getString(R.string.dialog_choose_cancel), stringArrayList);
        iosSingleChooseDialog.setOnIosSingleChooseItemClickListener(this);
        iosSingleChooseDialog.showAtLocation(getWindow().getDecorView());
        lightof();
        iosSingleChooseDialog.setOnDismissListener(this::lighton);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == START_CAMERA_ACTIVITY) {
                /*
                 *  notify system scan the image file ,show the  album
                 */
                SystemActivityUtils.getInstance().notifySystemScanImageFile(this, mImageFilePath);
                //you can use this image
                if (mFeedBackPhotoListAdapter != null) {
                    FeedBackImageBean feedBackImageBean = new FeedBackImageBean.Builder().filePath(mImageFilePath).build();
                    mFeedBackPhotoListAdapter.addData(feedBackImageBean);
                }
            } else if (requestCode == START_ALBUM_ACTIVITY) {
                Uri imageUri = data.getData();
                String imageFilePath = UriUtils.getInstance().getRealPathFromURI(this, imageUri);
                //you can use this image
                if (mFeedBackPhotoListAdapter != null) {
                    FeedBackImageBean feedBackImageBean = new FeedBackImageBean.Builder().filePath(imageFilePath).build();
                    mFeedBackPhotoListAdapter.addData(feedBackImageBean);
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_PERMISSION_CODE:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission is granted. Continue the action or workflow
                    // in your app.
                    SystemActivityUtils.getInstance().startAlbumActivity(this, START_ALBUM_ACTIVITY);
                } else {
                    // Explain to the user that the feature is unavailable because
                    // the features requires a permission that the user has denied.
                    // At the same time, respect the user's decision. Don't link to
                    // system settings in an effort to convince the user to change
                    // their decision.
                    ToastUtils.showError(StringUtils.getInstance().getString(R.string.tip_please_open_the_camera_permission));
                }
                return;
            default:
                break;
        }
    }

    @Override
    public void onIosSingleChooseItemClick(String string, int position, int type) {
        if (type == 2) {
            /*
             * title click
             */
            mImageFilePath = SystemActivityUtils.getInstance().startCameraActivity(this, START_CAMERA_ACTIVITY);
        } else if (type == 0) {
            /*
             * other item open the album
             */

            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                // You can use the API that requires the permission.
                SystemActivityUtils.getInstance().startAlbumActivity(this, START_ALBUM_ACTIVITY);
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    // You can directly ask for the permission.
                    requestPermissions(permissions, REQUEST_PERMISSION_CODE);
                }
            }
        }
    }
}
